﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;
using System.Xml;
using Transformer.iHunter;

namespace Transformer.iHunter.Plugins.RssReader
{
    public class RssChannel : IChannel
    {
        private string uri;

        public RssChannel(string settings)
        {
            //settings:
            //
            //<RSS>
            //  <Uri>
            //      rss address
            //  </Uri>
            //</Rss>
            //

            XmlDocument xml = new XmlDocument();
            xml.LoadXml(settings);
            uri = xml.DocumentElement["Uri"].InnerText;
        }

        #region IChannel Members

        IEnumerable<IMessage> IChannel.DownloadMessages(DateTime startTime, DateTime endTime, string attachmentDirectoryPath)
        {
            XmlDocument xml = new XmlDocument();
            string content = string.Empty;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
                request.Method = "GET";
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                    {

                        content = sr.ReadToEnd();

                        xml.LoadXml(content);
                    }
                }

                // The first child of a standard XML document is the XML declaration.
                // The following code assumes and reads the first child as the XmlDeclaration.
                if (xml.FirstChild.NodeType == XmlNodeType.XmlDeclaration)
                {
                    // Get the encoding declaration.
                    XmlDeclaration decl = (XmlDeclaration)xml.FirstChild;
                    string encoding = decl.Encoding;

                    request = (HttpWebRequest)WebRequest.Create(uri);
                    request.Method = "GET";
                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    {
                        using (StreamReader sr = new StreamReader(response.GetResponseStream(),Encoding.GetEncoding(encoding)))
                        {

                            content = sr.ReadToEnd();

                            xml.LoadXml(content);
                        }
                    }
                }

            }
            catch
            {
                yield break;
            }
            finally
            {

            }
            foreach (XmlElement ele in xml.DocumentElement["channel"].GetElementsByTagName("item"))
            {
                if (ele["pubDate"] == null || DateTime.Parse(ele["pubDate"].InnerText) >= startTime && DateTime.Parse(ele["pubDate"].InnerText) <= endTime)
                {
                    int hashcode;
                    string title = string.Empty, author = string.Empty, link = string.Empty;
                    DateTime pubtime = DateTime.MinValue;

                    if (ele["title"] != null)
                        title = ele["title"].InnerText;

                    if (ele["author"] != null)
                        author = ele["author"].InnerText;

                    if (ele["link"] != null)
                        link = ele["link"].InnerText;

                    if (ele["pubDate"] != null)
                    {
                        pubtime = DateTime.Parse(ele["pubDate"].InnerText);
                    }

                    if (link != string.Empty)
                    {
                        hashcode = link.GetHashCode();
                    }
                    else if (ele["guid"] != null)
                    {
                        hashcode = ele["guid"].InnerText.GetHashCode();
                    }
                    else
                    {
                        hashcode = (title + author + pubtime.ToString()).GetHashCode();
                    }

                    Message msg = new Message(Guid.Empty, hashcode);

                    msg.Title = title;
                    msg.Author = author;
                    msg.PublishTime = pubtime;
                    msg.UpdateTime = pubtime;

                    if (ele["category"] != null)
                        msg.Category = ele["category"].InnerText;

                    if (ele["description"] != null)
                        msg.Content = ele["description"].InnerText;

                    if (link != string.Empty)
                        msg.Content += "<br /><br />Link: <a href = \"" + link + "\">" + link + "</a>";

                    yield return msg;
                }
            }
            yield break;

        }



        bool IChannel.SendMessage(IMessage message)
        {
            return false;
        }

        bool IChannel.ReplyMessage(IMessage orginal, IMessage reply)
        {
            return false;
        }

        void IChannel.CancelBlockingCall()
        {
            //do nothing now
        }

        public event PluginErrorEventHandler ErrorOccur;

        public bool DownloadAttachment(IAttachment attachment)
        {
            return true;
        }

        #endregion

        #region IDisposable 成员

        public void Dispose()
        {
        }

        #endregion

        #region IChannel Members


        public IEnumerable<IMessage> UpdateMessage(IMessage message)
        {
            yield break;
        }

        #endregion
    }
}
